import {Navigate, useLocation} from 'react-router-dom';
import React, {useEffect, useState} from 'react';
import {UserInfoType} from "@src/services/userinfo.ts"


type Props = {
    children: React.ReactNode;
};

// 创建一个路由守卫组件
const PrivateRoute = ({children}: Props) => {
    const location = useLocation(); // 获取当前路由信息
    const UserData = localStorage.getItem('UserData');
    const [content, setContent] = useState<React.ReactNode>(<div></div>);
    useEffect(() => {
        if (UserData == null) {
            setContent(<Navigate to="/login" replace state={{from: location}}/>);
        } else if (location.pathname == "/home/music/songsList" && location.state == null) {
            setContent(<Navigate to="/home/music" replace state={{from: location}}/>);
        } else if (location.pathname == "/home/music/search" && location.state == null) {
            setContent(<Navigate to="/home/music/searchSuggest" replace state={{from: location}}/>);
        } else if (location.pathname == "/home/news" || location.pathname == "/userinfo") {
            const {user}: UserInfoType = JSON.parse(UserData)
            if (user.isVisitor == true) {
                setContent(<Navigate to="/login" replace state={{from: location}}/>)
            } else {
                setContent(children)
            }
        } else if (location.pathname == "/home/chatRoom/chatRoomDetailed" && location.state == null) {
            setContent(<Navigate to="/home/chatRoom" replace state={{from: location}}/>);
        } else {
            setContent(children)
        }
    }, [location])

    return content

};

export default PrivateRoute;